package core;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import exception.ServerDownException;

/**
 * Crops an image.
 * @author Santiago Castillo
 */
public class Crop 
{
	// Constants
	/**
	 * Dimension to witch image will be cropped.
	 */
	private static final int DIMENSION = 96;
	
	// Methods
	public static void cropImage(File image, String savePath, String name, String type) throws ServerDownException
	{
		// Load image.
		BufferedImage img = null;
		Graphics2D g;
		
		try
		{
			img = ImageIO.read(image);
		}
		catch(IOException e)
		{
			throw new ServerDownException("CropERR - File format: " + image.getPath());
		}
		
		if(img != null)
		{
			int h = img.getHeight();
			int w = img.getWidth();
			int dim = h;
			
			if(h != DIMENSION || w != DIMENSION)
			{
				BufferedImage nImg;
				
				if(h != w)
				{
					// Image must be sliced.
					int dw = 0;
					int dh = 0; 
					
					if(h < w)
					{
						dw = (w - h)/2;
					}
					else
					{
						dh = (h - w)/2;
						dim = w;
					}
					
					nImg = new BufferedImage(dim, dim, img.getType());
					g = nImg.createGraphics();
					g.drawImage(img, 0, 0, dim, dim, dw, dh, dw + dim, dh + dim, null);
					g.dispose();
					img = nImg;
				}
				
				// Image is resized.
				nImg = new BufferedImage(DIMENSION, DIMENSION, img.getType());
				g = nImg.createGraphics();
				g.drawImage(img, 0, 0, DIMENSION, DIMENSION, 0, 0, dim, dim, null);
				g.dispose();
				img = nImg;
				
				// Save new image.
				try
				{
					ImageIO.write(img, type, new File(savePath + "/" + name));
				}
				catch(IOException e)
				{
					throw new ServerDownException("CropERR - Write: " + savePath + "/" + name);
				}
			}				
		}
	}
}
